package com.itheima.history.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.history.config.RabbitConfig;
import com.itheima.history.service.HistorService;
import com.itheima.history.util.CookieUtil;
import com.itheima.util.IdWorker;
import com.netflix.ribbon.proxy.annotation.Http;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController()
@RequestMapping("/history")
public class HistoryController {
    final static String preHistory = "history_search_";
    final static String nologin = "nologin_";
    final static String login = "login_";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private HistorService historService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/findHistory")
    public Result findHistory(@RequestParam(value = "phone", required = false) String phone) {
        return historService.findHistory(phone);
    }


    @PostMapping("/addHistory")
    public Result addHistory(@RequestParam(value = "phone", required = false) String phone,
                             @RequestParam("productName") String productName,
                             HttpServletResponse response) {
        Result history = historService.findHistory(phone);


        sendMessage((Set<String>) history.getData(), productName);

        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] cookies = request.getCookies();
        if (phone == null) {
            //未登陆
            //第一次访问
            String value = nologin + idWorker.nextId();
            if (cookies == null) {
                CookieUtil.addCookie(response, "", "/", preHistory,
                        value, 30 * 60 * 60, false);

                redisTemplate.boundSetOps(value).add(productName);
                return new Result(true, StatusCode.OK, "添加成功");
            }
            //有记录
            for (Cookie cookie : cookies) {
                if (preHistory.equals(cookie.getName())) {
                    redisTemplate.boundSetOps(cookie.getValue()).add(productName);
                    break;
                }
            }

        } else {
            //登陆
            String value = login + phone;
            //第一次访问
            if (cookies == null) {
                CookieUtil.addCookie(response, "", "/", preHistory,
                        value, 30 * 60 * 60, false);

                redisTemplate.boundSetOps(value).add(productName);
                return new Result(true, StatusCode.OK, "添加成功");
            }
            //有记录
            for (Cookie cookie : cookies) {
                if (preHistory.equals(cookie.getName())) {
                    //合并历史记录
                    String value_ = cookie.getValue();
                    if (value_.startsWith(nologin)) {
                        //合并
                        //第一次登陆 重置之前的cookie
                        CookieUtil.addCookie(response, "", "/", preHistory,
                                value, 30 * 60 * 60, false);
                        Set members = redisTemplate.boundSetOps(value_).members();
                        //删除旧redis
                        redisTemplate.delete(value_);
                        //加入新redis
                        for (Object member : members) {
                            redisTemplate.boundSetOps(value).add(member);
                        }
                        redisTemplate.boundSetOps(value).add(productName);
                        break;
                    } else {
                        redisTemplate.boundSetOps(value).add(productName);
                        break;
                    }
                }
            }
        }
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @RequestMapping("/delByName")
    public Result delByName(@RequestParam(value = "phone", required = false) String phone,
                            @RequestParam("productName") String productName) {
        if (!StringUtils.isEmpty(phone)) {
            String key = login + phone;
            redisTemplate.boundSetOps(key).remove(productName);
            return new Result(true, StatusCode.OK, "删除成功");
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (preHistory.equals(cookie.getName())) {
                redisTemplate.boundSetOps(cookie.getValue()).remove(productName);
                return new Result(true, StatusCode.OK, "删除成功");
            }
        }
        return new Result(true, StatusCode.OK, "删除失败");
    }

    private void sendMessage(Set<String> oldList, String newName) {
        HashMap map = new HashMap();
        map.put("newProduct", newName);
        map.put("oldList", oldList);
        String json = JSON.toJSONString(map);
        rabbitTemplate.convertAndSend("", RabbitConfig.QUEUE_HISTORY, json);
    }


}
